package com.bestcem.xm.user.service.impl;

import cn.hutool.core.lang.ObjectId;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.enums.ReqErrorCodeEnum;
import com.bestcem.xm.user.dao.UserUserRoleDao;
import com.bestcem.xm.user.entity.mysql.UserUserRole;
import com.bestcem.xm.user.entity.pojo.UserUserRoleDO;
import com.bestcem.xm.user.service.RoleService;
import com.bestcem.xm.user.service.UserUserRoleService;
import com.bestcem.xm.user.service.dto.user.UserUserRoleDTO;
import com.bestcem.xm.user.util.business.DataBaseUtil;
import com.bestcem.xm.user.util.business.UserJwtTokenUtil;
import com.bestcem.xm.user.util.convert.UserUserRoleConvert;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户与角色的关联业务
 *
 * @author wangyunyun <yunyun.wang@idiaoyan.com>
 * @version v1.0
 * @date 2023/3/4 14:30
 */
@Slf4j
@Service
public class UserUserRoleServiceImpl implements UserUserRoleService {

    @Resource
    private UserUserRoleConvert userUserRoleConvert;

    @Resource
    private RoleService roleService;

    @Autowired
    private UserUserRoleDao userUserRoleDao;


    @Resource
    private UserJwtTokenUtil userJwtTokenUtil;

    //@Resource
    //private UserMessageSender userMessageSender;

    @Override
    public ServiceResult<List<UserUserRoleDTO>> listByCondition(UserUserRoleDTO userUserRoleDTO) {
        // 校验参数
        if (userUserRoleDTO == null) {
            return ServiceResult.fail("参数不能为空");
        }
        // 查询
        return ServiceResult.success(userUserRoleConvert
                .dos2Dtos(userUserRoleDao.listByCondition(userUserRoleConvert.dto2Do(userUserRoleDTO))));
    }

    @Override
    public ServiceResult<String> insert(UserUserRoleDTO userUserRoleDTO) {
        return ServiceResult.success(userUserRoleDao.insertSelective(userUserRoleConvert.dto2Do(userUserRoleDTO)));
    }

    /**
     * 根据userId删除用户与角色的关联关系
     *
     * @param userId
     * @return com.bestcem.xm.util.ServiceResult<java.lang.Object>
     * @author panyun <yun.pan@idiaoyan.com>
     * @date 2022/3/9 10:37
     */
    @Override
    public ServiceResult<Object> deleteByUserId(String userId) {
        if (!ObjectId.isValid(userId)) {
            return ServiceResult.fail(ReqErrorCodeEnum.PARAM_RANGE, "userId单位是不正确");
        }

        userUserRoleDao.deleteByUserId(userId);
        return ServiceResult.success();
    }

    @Override
    public ServiceResult<Object> insertUserRoleList(String orgId, String userId, List<String> roleIdList, String currentId) {
        ArrayList<UserUserRole> userUserRoles = new ArrayList<>();
        for (String roleId : roleIdList) {
            UserUserRole userUserRole = new UserUserRole();
            userUserRole.setUserRoleId(DataBaseUtil.generateId());
            userUserRole.setUserId(userId);
            userUserRole.setRoleId(roleId);
            userUserRole.setOrgId(orgId);
            if (Objects.nonNull(currentId)) {
                userUserRole.setOperatorId(currentId);
                userUserRole.setCreatorId(currentId);
            }
            userUserRoles.add(userUserRole);
        }
        userUserRoleDao.insertUserRoleList(userUserRoles);
        return ServiceResult.success();
    }

    @Override
    public List<String> listByRoleIdList(List<String> roleIdsList) {
        return userUserRoleDao.listByRoleIds(roleIdsList);
    }

    @Override
    public ServiceResult<List<String>> listUserIdsByRoleId(String roleId) {
        List<String> list = new ArrayList<>();
        list.add(roleId);
        return ServiceResult.success(listByRoleIdList(list));
    }

    @Override
    public ServiceResult<List<String>> listRoleIdsByUserId(String userId) {
        return ServiceResult.success(userUserRoleDao.listRoleIdByUserId(userId));
    }

    @Override
    public ServiceResult<Boolean> updateRoleUsers(String orgId, String roleId, List<String> userIds, String operateUserId) {
        List<String> roleIds = new ArrayList<>();
        roleIds.add(roleId);
        userIds = Objects.isNull(userIds) ? new ArrayList<>() : userIds;
        List<String> aleradyUserIds = listByRoleIdList(roleIds);
        List<String> temp = new ArrayList<>(aleradyUserIds);

        // 获取需要删除的
        temp.removeAll(userIds);
        if (CollectionUtils.isNotEmpty(temp)) {
            userUserRoleDao.deleteByRoleIdAndUserIds(orgId, roleId, temp);
        }

        // 获取需要新增的
        userIds.removeAll(aleradyUserIds);
        if (CollectionUtils.isNotEmpty(userIds)) {
            for (String userId : userIds) {
                UserUserRoleDO userUserRoleDO = new UserUserRoleDO();
                userUserRoleDO.setCreatorId(operateUserId);
                userUserRoleDO.setOperatorId(operateUserId);
                userUserRoleDO.setUserId(userId);
                userUserRoleDO.setRoleId(roleId);
                userUserRoleDO.setOrgId(orgId);
                userUserRoleDao.insertSelective(userUserRoleDO);
            }
        }

        return ServiceResult.success(true);
    }

    @Override
    public ServiceResult<Boolean> checkUserRoleChangeAndUpdate(String orgId, String userId, List<String> newRoleIdList, List<String> oldRoleIdList, String currentId) {
        String oldRoleStr = "";
        String newRoleStr = "";
        if (CollectionUtils.isNotEmpty(oldRoleIdList)) {
            oldRoleStr = oldRoleIdList.stream().sorted().collect(Collectors.joining());
        }
        if (CollectionUtils.isNotEmpty(newRoleIdList)) {
            newRoleStr = newRoleIdList.stream().sorted().collect(Collectors.joining());
        }

        // 用户角色是否变化
        if (!oldRoleStr.equals(newRoleStr)) {
            // 更新角色权限
            if (CollectionUtils.isNotEmpty(oldRoleIdList)) {
                userUserRoleDao.deleteByRoleIdList(userId, oldRoleIdList);
            }
            if (CollectionUtils.isNotEmpty(newRoleIdList)) {
                insertUserRoleList(orgId, userId, newRoleIdList, currentId);
            }
            return ServiceResult.success(Boolean.TRUE);
        }
        return ServiceResult.success(Boolean.FALSE);

    }

    @Override
    public ServiceResult<Boolean> checkSeniorRole(String orgId, String userId, List<String> newRoleIdList, List<String> oldRoleIdList) {
        if (CollectionUtils.isEmpty(oldRoleIdList) && CollectionUtils.isEmpty(newRoleIdList)) {
            return ServiceResult.success();
        }
        //  高级管理员角色id
        ServiceResult<String> seniorRoleResult = roleService.getSeniorAdminRole(orgId);
        String seniorRoleId = seniorRoleResult.getData();
        // 添加高级管理员权限则添加高级管理员项目入口
        if (CollectionUtils.isNotEmpty(newRoleIdList) &&
                (CollectionUtils.isEmpty(oldRoleIdList) || !oldRoleIdList.contains(seniorRoleId)) &&
                newRoleIdList.contains(seniorRoleId)) {
            //userMessageSender.publishSeniorRoleChanged(orgId);
            // 更新用户的token版本号
            userJwtTokenUtil.updateTokenVersion(userId);
        }
        // 移除高级管理员权限则删除高级管理员项目入口
        if (CollectionUtils.isNotEmpty(oldRoleIdList) &&
                (CollectionUtils.isEmpty(newRoleIdList) || !newRoleIdList.contains(seniorRoleId)) &&
                oldRoleIdList.contains(seniorRoleId)) {
            //userMessageSender.publishSeniorRoleChanged(orgId);
            // 更新用户的token版本号
            userJwtTokenUtil.updateTokenVersion(userId);
        }
        return ServiceResult.success();
    }

    @Override
    public ServiceResult<Integer> updateSelectiveById(UserUserRoleDTO userUserRoleDTO) {
        if (Objects.isNull(userUserRoleDTO)) {
            return ServiceResult.fail(ReqErrorCodeEnum.PARAM_LOST, "参数信息不能为空");
        }
        Integer integer = userUserRoleDao.updateSelectiveById(userUserRoleConvert.dto2Do(userUserRoleDTO));
        return ServiceResult.success(integer);
    }

    @Override
    public ServiceResult<Integer> deleteByRoleId(String roleId) {
        Integer result = userUserRoleDao.deleteByRoleId(roleId);
        return ServiceResult.success(result);
    }
}
